/*
 $(document).ready(function() 
 	{ 
 		$("table") 
 	    .tablesorter({widthFixed: true, widgets: ['zebra']}) 
 	    .tablesorterPager({container: $("#pager")}); 
 		$("#frm").validationEngine();
         $( "#tabs" ).tabs();
         $( ".datepicker" ).datepicker();
 	} 
 );
 */
(function ($) {
    var SearchForm = function () {
        this.loadingContent = false;
        this.loadingSpotlight = false;
        this.loadingCheckContent = false;
        this.searchFormHeight = 123;
        this.searchMoreOptionHeight = 223;
        this.heightHeader = 60;
        this.heightHeaderShadow = 13;
        this.lastCouponItem = 0;
        this.positionProduct = 0;
        this.moreResult = false;
        this.loaded = 0;
        this.totalImages = 0;
        this.pageCount = 0;
        this.heightList = 0;
        this.advertisements = $('.spotlight-box div.spotlight:not(.eixternal)').size();
        this.userExistCompetition = false;
        this.currentStep = "home";
    };

    SearchForm.prototype.initSearchForm = function () {
    	var self = this;
        
        var index = 1;
        $('.add-appraisal').live('click', function(e){
            e.preventDefault();
            var _this = $(this).parent().children().first();
            if(_this.val() == '' || _this.val() == null){
                alert('You must select the date');  
            }
            else
            {
                var parentAppraisal = $('.control-appraisal').parent();
                var controlAppraisal = '<div class="controls control-appraisal">';
    	            controlAppraisal += '<input type="text" id="dpappraisal'+index+'" name="AppraisalDate[]" placeholder="Yearly Appraisal" class="datepicker" />';
                    controlAppraisal += '&nbsp;&nbsp;&nbsp;<span>Remark</span>&nbsp;<input type="text" name="AppraisalComment[]" placeholder="Remark" />&nbsp;&nbsp;<a class="delete-element" href="#">Delete</a> | <a class="add-appraisal" href="#">Add</a>';
    	            controlAppraisal += '</div>';
                parentAppraisal.append(controlAppraisal);
                 $('#dpappraisal'+index).datepicker({ dateFormat: "yy-mm-dd" }).val();
                index++;
            }
        });
        
        $('.add-sal-increase').live('click', function(e){
            e.preventDefault();
            var _this = $(this).parent().children().first();
            if(_this.val() == '' || _this.val() == null){
                alert('You must select the date');  
            }
            else
            {
                var parentAppraisal = $('.control-sal-increase').parent();
                var controlAppraisal = '<div class="controls control-sal-increase">';
    	            controlAppraisal += '<input type="text" id="dpincreasedsalary'+index+'" name="IncreasedDate[]" placeholder="Salary Increase" class="datepicker" />';
                    controlAppraisal += '&nbsp;&nbsp;&nbsp;<span>Remark</span>&nbsp;<input type="text" name="SalaryIncreaseComment[]" placeholder="Remark" />&nbsp;&nbsp;<a class="delete-element" href="#">Delete</a> | <a class="add-sal-increase" href="#">Add</a>';
    	            controlAppraisal += '</div>';
                parentAppraisal.append(controlAppraisal);
                $('#dpincreasedsalary'+index).datepicker({ dateFormat: "yy-mm-dd" }).val();
                index++;
            }
        });
        
        $('.add-amendment').live('click', function(e){
            e.preventDefault();
             var _this = $(this).parent().children().first();
            if(_this.val() == '' || _this.val() == null){
                alert('You must select the date');  
            }
            else
            {
                var parentAmendment = $('.control-amendment').parent();
                var controlAmendment = '<div class="controls control-amendment">';
    	            controlAmendment += '<input type="text" id="dpamendment'+index+'" name="AmendmentDate[]" placeholder="Amendment" class="datepicker" />';
                    controlAmendment += '&nbsp;&nbsp;&nbsp;<span>Remark</span>&nbsp;<input type="text" name="AmendmentComment[]" placeholder="Remark" />&nbsp;&nbsp;<a class="delete-element" href="#">Delete</a> | <a class="add-amendment" href="#">Add</a>';
    	            controlAmendment += '</div>';
                parentAmendment.append(controlAmendment);
                $('#dpamendment'+index).datepicker({ dateFormat: "yy-mm-dd" }).val();
                index++;
            }
        });
        
        $('.delete-element').live('click', function(e) {
            e.preventDefault();
            $(this).parent().remove();
        });
        $('.contract-type').change(function() {
            if($(this).val() == 2){
                $('.control-end-contract').css('display','none');
            }else{
                $('.control-end-contract').css('display','block');
            }
        });
    	if($('#content-left').hasClass('class-left-report')){
    	   $('.content-margin-left').attr('class','content-margin-left-report');
    	}
    }
    SearchForm.prototype.slideToggle = function(e) {
    	$(e).slideToggle();
    }
    SearchForm.prototype.dropdownAutoComplete = function() {
        $("#dropdown-town").autocomplete({ appendTo: ".auto-complete-town-box" });
        var appendTo = $("#dropdown-town").autocomplete("option", "appendTo");
        var autoFocus = $("#dropdown-town").autocomplete("option", "autoFocus");
        $("#dropdown-town").autocomplete("option", "appendTo", ".auto-complete-town-box");
        $("#dropdown-town").autocomplete( "option", "autoFocus", true );
        $("#dropdown-town").autocomplete({
            minLength: 3,
            //autoFocus:true,
            source: function (request, response) {
                var itemArray = request.term.split(';');
                var itemLast = itemArray[itemArray.length-1];
                var finalSuburb = request.term;
                if(itemArray.length > 0) {
                    finalSuburb = itemLast;
                }
                if(finalSuburb != "" && finalSuburb.length >= 3){
                    $.ajax({
                        url: "/search/getsuburbs", type: "POST", dataType: "json",
                        data: { suburbName: $.trim(finalSuburb), maxResults: 14 },
                        success: function (data) {
                            response($.ui.autocomplete.filter(data, extractLast($.trim(finalSuburb))));
                        }
                    })
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( "; " );
                return false;
            }
        });
    }
    SearchForm.prototype.checkBroswer = function() {
        if($.browser.msie && parseInt($.browser.version) <= 6) {
            return true;
        }
            return false;
    }
    SearchForm.prototype.closeToolbox = function () {
        $('.toolbox').animate({'width': 0}, 500, function () {
            $('.toolbox-inner').hide();
            $('.close-toolbox').hide();
        });
    }
    SearchForm.prototype.eventBoxPopup = function() {
        var self = this;
        $('.box-popup').hide();
        $('#box-docketbook').hide();
        $('#box-printall').hide();
        $('.header-login, .mobile-only-login').live('click', function(e){
            e.preventDefault();
            self.showMask();
            $('.loading-box').show();
            $.ajax({
                url: "/Login/RenderFormView", type: "POST",
                data: {viewName: '/Views/Shared/ConsumerControls/_Login.cshtml', type: 'Login'},
                success: function (data) {
                    $('#wrapper').append(data);
                    $('.loading-box').hide();
                    self.showFormLogin();
                    self.showMask();
                    self.initSearchForm();
                    self.actionPopupBox();
                    if($('#box-popup-message').length){
                         $('#box-popup-message').fadeOut('slow');
                         $('#box-popup-message').find('h3, .bottom-mobile-only').remove();
                         $('#box-popup-message').find('.result').text('');
                    }
                }});
        })

        $('.close-popup-myprofile').live('click', function(e){
            e.preventDefault();
            self.hideFormMyProfile();
            self.hideMask();
        })
    }

    SearchForm.prototype.checkScrollPopup = function() {
        $('.section-box-detail ul li').each(function(){
            $(this).ajaxComplete(function() {
                var boxDetailH = $(this).parent('ul');
                if($('.section-box-detail ul').height() <= 220){
                    $('.section-box-detail').css('overflow','hidden');
                }
                else{
                    $('.section-box-detail').css('overflow-y','scroll');
                }
            });
        });
    }

    /**
    * Refine Search
    */
    var RefineSearchForm = function () {
        
    }

    RefineSearchForm.prototype.initRefineSearchForm = function() {
        var self = this;
        $('.advanced-search').click(function (e) {
            e.preventDefault();
            $('.search-form').addClass('search-form-options');
            $('.search-more-options').addClass('search-less-options');
            $('.refine-search').fadeOut('fast', function() {
                $('.product-list h1').css('border-bottom', '1px solid #C4122F');
            });
            self.searchForm.expandSearchPanel();
        });
    }

    //
    /*
    the images preload plugin
    */
    $.fn.preload = function(options) {
        var opts = $.extend({}, $.fn.preload.defaults, options),
            o = $.meta ? $.extend({}, opts, this.data()) : opts;
        return this.each(function() {
            var $e = $(this),
                t = $e.attr('src'),
                l = 0;
            $('<img/>').load(function(i){
                ++l;
                if(l==1) o.onComplete();
            }).error(function(i) {
                $e.attr({'src': '/images/print-empty-image.gif', 'width':'330px', 'height':'220px'});
                $(this).trigger('load');
            })
            .attr('src',t);
        });
    };
    $.fn.preload.defaults = {
        onComplete : function(){return false;}
    };
    
    jQuery(function ($) {
        var searchForm = new SearchForm();
        searchForm.initSearchForm();
        
        $(".tablesorter") 
	    .tablesorter({widthFixed: true, widgets: ['zebra']}) 
	    .tablesorterPager({container: $("#pager")}); 
		$("#frm").validationEngine();
        $( "#tabs" ).tabs();
        /**current tab**/
        var currentUrl = window.location.href;
        var currentLi = 'ui-tabs-selected ui-state-active';
        var currentTab = currentUrl.substring(currentUrl.length-6);
        $('.'+currentLi).removeClass(currentLi);
        $('.'+currentTab).addClass(currentLi);
        
        $( ".datepicker" ).datepicker({ dateFormat: "yy-mm-dd" }).val();
        
        $('.setting-box').hide();
    	if($('.btn-cancel').length) {
            $('.btn-cancel').click(function(e) {
               history.back();
            });
        }
    	$('.setting').click(function(e) {
    		searchForm.slideToggle('.setting-box');
    	});
        $('.img-popup').click(function() {
    		var url = $(this).attr('src');
            windowPopup(url);
    	});
        $('.link-popup').click(function(e) {
           var url = $(this).parent().attr('href'); 
           windowPopup(url);
           return false;
        });
        $('.delete-item').live('click',function() {
    		return confirm('Are you sure want to delete this item?');
    	});
        
        function windowPopup(url)
        {
            window.open(url, null, "width=700, height=500, scrollbars=yes");
            return false;   
        }
        
      });

   $(window).load(function () {
		/**
 * $('ul.product-box li div.box-images .box-images-inner img').each(function() {
 *             var imageH = parseInt($(this).height());
 *             if(imageH <= 100){
 *                 var imageT = (110 - imageH) / 2;
 *                 $(this).css('margin-top',imageT);
 *             }
 *         });
 *         function GetURLParameter(){
 *             var sPageURL=window.location.search.substring(1);
 *                 var sParameterName = sPageURL.split('=');
 *                 var sParameterValue=sParameterName[1];
 *                 if(sParameterValue == 'Register'){
 *                     $('.docket-login .header-register').trigger('click');
 *                 }else if(sParameterValue == 'competlog'){
 *                     $('.enter-here').trigger('click');
 *                 }else{
 *                 }
 *         }
 *         GetURLParameter();
 *         if($('.banner-collapse-inner ul.rotated li').length){
 *             $('.content-left').css({'margin-top':'266px'});
 *         }
 *         else{
 *             $('.content-left').css({'margin-top':'0px'});
 *         }
 */
   });
})(jQuery);